Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [1]:
# Load pickled data
import pickle

# TODO: Fill this in based on where you saved the training and testing data

training_file = './data/train.p'
validation_file= './data/valid.p'
testing_file = './data/test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [2]:
import numpy as np
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results

# Number of training examples
n_train = X_train.shape[0]

# Number of validation examples
n_validation = X_valid.shape[0]

# Number of testing examples.
n_test = X_test.shape[0]

# What's the shape of an traffic sign image?
image_shape = X_train.shape[1:]

# How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_train))

print("Number of training examples =", n_train)
print("Number of validation examples=", n_validation)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of validation examples= 4410
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?

In [3]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline

# Define the show_images function - show images for testing
def show_images(images, cols = 10, cmap=None):
    rows = (len(images)+1)//cols
    fig, axs = plt.subplots(rows,cols, figsize=(18, rows * 2))
    fig.subplots_adjust(hspace = .1, wspace=.001)
    axs = axs.ravel()
    for i, img in enumerate(images):
        axs[i].axis('off')
        if(len(img.shape) == 2):
            cmap = 'gray'
            axs[i].imshow(img.squeeze(), cmap)
        else:
            axs[i].imshow(img, cmap)

show_images(X_train[60:80])
        
In [4]:
# histogram of label frequency
hist, bins = np.histogram(y_train, bins=n_classes)
center = (bins[:-1] + bins[1:]) / 2
plt.title("Distribution of train dataset")
plt.xlabel("Class number")
plt.ylabel("No image")
plt.bar(center, hist)
plt.show()
In [5]:
import random
from pandas.io.parsers import read_csv

SEED = 1501
random.seed(SEED)

signnames = read_csv("signnames.csv").values[:, 1]

col_width = max(len(name) for name in signnames)

sign_classes, class_indices, class_counts = np.unique(y_train, return_index = True, return_counts = True)

for c, c_index, c_count in zip(sign_classes, class_indices, class_counts):
    print("Class %i: %-*s  %s samples" % (c, col_width, signnames[c], str(c_count)))
    fig = plt.figure(figsize = (18, 3))
    fig.subplots_adjust(left = 0, right = 1, bottom = 0, top = 1, hspace = 0.05, wspace = 0.05)
    random_indices = random.sample(range(c_index, c_index + c_count), 10)
    for i in range(10):
        axis = fig.add_subplot(1, 10, i + 1, xticks=[], yticks=[])
        axis.imshow(X_train[random_indices[i]])
    plt.show()
    print("--------------------------------------------------------------------------------------\n")
    
Class 0: Speed limit (20km/h)                                180 samples
--------------------------------------------------------------------------------------

Class 1: Speed limit (30km/h)                                1980 samples
--------------------------------------------------------------------------------------

Class 2: Speed limit (50km/h)                                2010 samples
--------------------------------------------------------------------------------------

Class 3: Speed limit (60km/h)                                1260 samples
--------------------------------------------------------------------------------------

Class 4: Speed limit (70km/h)                                1770 samples
--------------------------------------------------------------------------------------

Class 5: Speed limit (80km/h)                                1650 samples
--------------------------------------------------------------------------------------

Class 6: End of speed limit (80km/h)                         360 samples
--------------------------------------------------------------------------------------

Class 7: Speed limit (100km/h)                               1290 samples
--------------------------------------------------------------------------------------

Class 8: Speed limit (120km/h)                               1260 samples
--------------------------------------------------------------------------------------

Class 9: No passing                                          1320 samples
--------------------------------------------------------------------------------------

Class 10: No passing for vehicles over 3.5 metric tons        1800 samples
--------------------------------------------------------------------------------------

Class 11: Right-of-way at the next intersection               1170 samples
--------------------------------------------------------------------------------------

Class 12: Priority road                                       1890 samples
--------------------------------------------------------------------------------------

Class 13: Yield                                               1920 samples
--------------------------------------------------------------------------------------

Class 14: Stop                                                690 samples
--------------------------------------------------------------------------------------

Class 15: No vehicles                                         540 samples
--------------------------------------------------------------------------------------

Class 16: Vehicles over 3.5 metric tons prohibited            360 samples
--------------------------------------------------------------------------------------

Class 17: No entry                                            990 samples
--------------------------------------------------------------------------------------

Class 18: General caution                                     1080 samples
--------------------------------------------------------------------------------------

Class 19: Dangerous curve to the left                         180 samples
--------------------------------------------------------------------------------------

Class 20: Dangerous curve to the right                        300 samples
--------------------------------------------------------------------------------------

Class 21: Double curve                                        270 samples
--------------------------------------------------------------------------------------

Class 22: Bumpy road                                          330 samples
--------------------------------------------------------------------------------------

Class 23: Slippery road                                       450 samples
--------------------------------------------------------------------------------------

Class 24: Road narrows on the right                           240 samples
--------------------------------------------------------------------------------------

Class 25: Road work                                           1350 samples
--------------------------------------------------------------------------------------

Class 26: Traffic signals                                     540 samples
--------------------------------------------------------------------------------------

Class 27: Pedestrians                                         210 samples
--------------------------------------------------------------------------------------

Class 28: Children crossing                                   480 samples
--------------------------------------------------------------------------------------

Class 29: Bicycles crossing                                   240 samples
--------------------------------------------------------------------------------------

Class 30: Beware of ice/snow                                  390 samples
--------------------------------------------------------------------------------------

Class 31: Wild animals crossing                               690 samples
--------------------------------------------------------------------------------------

Class 32: End of all speed and passing limits                 210 samples
--------------------------------------------------------------------------------------

Class 33: Turn right ahead                                    599 samples
--------------------------------------------------------------------------------------

Class 34: Turn left ahead                                     360 samples
--------------------------------------------------------------------------------------

Class 35: Ahead only                                          1080 samples
--------------------------------------------------------------------------------------

Class 36: Go straight or right                                330 samples
--------------------------------------------------------------------------------------

Class 37: Go straight or left                                 180 samples
--------------------------------------------------------------------------------------

Class 38: Keep right                                          1860 samples
--------------------------------------------------------------------------------------

Class 39: Keep left                                           270 samples
--------------------------------------------------------------------------------------

Class 40: Roundabout mandatory                                300 samples
--------------------------------------------------------------------------------------

Class 41: End of no passing                                   210 samples
--------------------------------------------------------------------------------------

Class 42: End of no passing by vehicles over 3.5 metric tons  210 samples
--------------------------------------------------------------------------------------


Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.

Other pre-processing steps are optional. You can try different techniques to see if it improves performance.

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [ ]:
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.

# Normallize data step
# Comparte between standardlise and normalised
# Reference https://github.com/jessicayung/self-driving-car-nd/blob/master/p2-traffic-signs/Traffic_Sign_Classifier.ipynb
# https://stats.stackexchange.com/questions/211436/why-do-we-normalize-images-by-subtracting-the-datasets-image-mean-and-not-the-c

# Histogram equalizer

# Argumentation would help better
# https://medium.com/@gruby/convolutional-neural-network-for-traffic-sign-classification-carnd-e46e95453899

# Flipping

# Noise, Projection and Rotation
# https://github.com/NikolasEnt/Traffic-Sign-Classifier/blob/master/Traffic_Sign_Classifier-2Net.ipynb
In [6]:
import cv2

# show images for debug
def show2images(image1, image1title, image2, image2title):
    fig, axs = plt.subplots(1,2, figsize=(10, 3))
    axs = axs.ravel()

    axs[0].axis('off')
    axs[0].set_title(image1title)
    axs[0].imshow(image1.squeeze(), cmap='gray')

    axs[1].axis('off')
    axs[1].set_title(image2title)
    axs[1].imshow(image2.squeeze(), cmap='gray')    

#Histogram Equalization 
def eq_Hist(image):
    image[:, :, 0] = cv2.equalizeHist(image[:, :, 0])
    image[:, :, 1] = cv2.equalizeHist(image[:, :, 1])
    image[:, :, 2] = cv2.equalizeHist(image[:, :, 2])
    return image

test_train = X_train[4]
test_hist = eq_Hist(test_train)
show2images(test_train, 'Original', test_hist, 'histogram')
In [7]:
def crop_image(image, shift=4):
    a = int(np.random.randint(shift)-shift/2)
    b = int(np.random.randint(shift)-shift/2)
    c_x,c_y, sh = int(image.shape[0]/2), int(image.shape[1]/2), int(image.size/2 - shift/2)
    return image[(c_x-sh+a):(c_x+sh+a),(c_y-sh+b):(c_y+sh+b)]

test_crop = crop_image(test_train)
show2images(test_train, 'Original', test_crop, 'Crop')
In [8]:
def scale_image(image):
    img2=image.copy()
    sc_y= np.random.uniform(1.0, 1.3)
    img2=cv2.resize(image, None, fx=1, fy=sc_y, interpolation = cv2.INTER_CUBIC)
    return img2

test_scale = scale_image(test_train)
show2images(test_train, 'Original', test_scale, 'Scaled')
In [9]:
def rotate_image(image):
    c_x,c_y = int(image.shape[0]/2), int(image.shape[1]/2)
    ang = 20.0*np.random.rand() - 10
    M = cv2.getRotationMatrix2D((c_x, c_y), ang, 1.0)
    rotated = cv2.warpAffine(image, M, image.shape[:2])
    return rotated

test_rotated = rotate_image(test_train)
show2images(test_train, 'Original', test_rotated, 'Rotated')
In [10]:
def sharpen_image(image):
    gb = cv2.GaussianBlur(image, (5,5), 15.0)
    return cv2.addWeighted(image, 2, gb, -1, 0)

test_sharpen = sharpen_image(test_train)
show2images(test_train, 'Normalized', test_sharpen, 'Sharpen')
In [11]:
def bright_image(image):
    image = cv2.cvtColor(image,cv2.COLOR_RGB2HSV)
    br = np.random.uniform(0.3, 1.0)
   
    image[:,:,2] = image[:,:,2]*br
    image = cv2.cvtColor(image,cv2.COLOR_HSV2RGB)
    return image

test_bright = bright_image(test_train)
show2images(test_train, 'Original', test_bright, 'Brighted')
In [12]:
def constract_image(image, c=1.4):
    m = 127.0 * (1.0 - c)
    img2=cv2.multiply(image, np.array([c]))
    constracted = cv2.add(img2, np.array([m]))
    return constracted
test_constracted = constract_image(test_train, 1.2)
show2images(test_train, 'Original', test_constracted, 'Constracted')
In [13]:
def transform_image(image, debug=False):
    hist = eq_Hist(image)
    sharpen=sharpen_image(hist)
    crop = crop_image(sharpen, 4)
    bright = bright_image(crop)
    constracted=constract_image(bright, 1.5)
    if debug:
        show2images(image, 'Original', hist, 'Histogram')
        show2images(sharpen, 'Sharpen', crop, 'Crop')
        show2images(bright, 'Bright', constracted, 'Transformed')
    return constracted

transformed = transform_image(test_train, True)
In [14]:
def augment_image(image, debug = False):
    #img=contr_img(img, 0.9*np.random.rand()+0.1)
    rotated=rotate_image(image)
    transformed = transform_image(rotated, debug)
    #translated =translate_image(transformed)
    #augmented = transform_image(translated, debug)
    if debug:
        show2images(image, 'Original', rotated, 'Rotated')
        show2images(rotated, 'Rotated', transformed, 'Transformed')
        print('Output size: ', transformed.shape)
    return transformed

test_aug = augment_image(test_train, False)
# try more on 30km/h
test_30 = X_train[y_train== 1][4]
test_30_aug = augment_image(test_30, True)
Output size:  (32, 32, 3)
In [15]:
# try to augrment 11 times for one image
show2images(test_30, 'Original', augment_image(test_30), 'Augmented')
show2images(augment_image(test_30), 'Augmented', augment_image(test_30), 'Augmented')
show2images(augment_image(test_30), 'Augmented', augment_image(test_30), 'Augmented')
show2images(augment_image(test_30), 'Augmented', augment_image(test_30), 'Augmented')
show2images(augment_image(test_30), 'Augmented', augment_image(test_30), 'Augmented')
show2images(augment_image(test_30), 'Augmented', augment_image(test_30), 'Augmented')
In [16]:
sign_classes, class_indices, class_counts = np.unique(y_train, return_index = True, return_counts = True)
X_train_aug = []
y_train_aug = []

n_aug = 5
for c, c_index, c_count in zip(sign_classes, class_indices, class_counts):
    print("Processing Class %i: %-*s  %s samples" % (c, col_width, signnames[c], str(c_count)))
    for i in range(c_index, c_index + c_count):
        img = X_train[i]
        y = y_train[i]
        X_train_aug.append(img)
        y_train_aug.append(y)
        if c_count < 1000:
            n_aug = 10
        for j in range(n_aug):
            X_train_aug.append(augment_image(img))
            y_train_aug.append(y)
        if i%10 == 0:
            print('-', end='')
        if i%50 == 0:
            print('|', end='')
    print("--------------------------------------------------------------------------------------\n")
print('Augment image size:', len(X_train_aug))
Processing Class 0: Speed limit (20km/h)                                180 samples
-----|-----|-----|-----------------------------------------------------------------------------------------

Processing Class 1: Speed limit (30km/h)                                1980 samples
----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 2: Speed limit (50km/h)                                2010 samples
--|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 3: Speed limit (60km/h)                                1260 samples
----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 4: Speed limit (70km/h)                                1770 samples
-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 5: Speed limit (80km/h)                                1650 samples
-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 6: End of speed limit (80km/h)                         360 samples
-|-----|-----|-----|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 7: Speed limit (100km/h)                               1290 samples
---|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|---------------------------------------------------------------------------------------

Processing Class 8: Speed limit (120km/h)                               1260 samples
----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 9: No passing                                          1320 samples
--|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 10: No passing for vehicles over 3.5 metric tons        1800 samples
---|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 11: Right-of-way at the next intersection               1170 samples
---|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 12: Priority road                                       1890 samples
---|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|---------------------------------------------------------------------------------------

Processing Class 13: Yield                                               1920 samples
-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 14: Stop                                                690 samples
----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 15: No vehicles                                         540 samples
-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 16: Vehicles over 3.5 metric tons prohibited            360 samples
-----|-----|-----|-----|-----|-----|-----|---------------------------------------------------------------------------------------

Processing Class 17: No entry                                            990 samples
-|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----------------------------------------------------------------------------------------

Processing Class 18: General caution                                     1080 samples
----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 19: Dangerous curve to the left                         180 samples
---|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 20: Dangerous curve to the right                        300 samples
-|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 21: Double curve                                        270 samples
---|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 22: Bumpy road                                          330 samples
-|-----|-----|-----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 23: Slippery road                                       450 samples
----|-----|-----|-----|-----|-----|-----|-----|-----|---------------------------------------------------------------------------------------

Processing Class 24: Road narrows on the right                           240 samples
-|-----|-----|-----|-----|-----------------------------------------------------------------------------------------

Processing Class 25: Road work                                           1350 samples
-|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 26: Traffic signals                                     540 samples
---|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|---------------------------------------------------------------------------------------

Processing Class 27: Pedestrians                                         210 samples
-|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 28: Children crossing                                   480 samples
-|-----|-----|-----|-----|-----|-----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 29: Bicycles crossing                                   240 samples
-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 30: Beware of ice/snow                                  390 samples
----|-----|-----|-----|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 31: Wild animals crossing                               690 samples
-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 32: End of all speed and passing limits                 210 samples
--|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 33: Turn right ahead                                    599 samples
-|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 34: Turn left ahead                                     360 samples
-----|-----|-----|-----|-----|-----|-----|---------------------------------------------------------------------------------------

Processing Class 35: Ahead only                                          1080 samples
---|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 36: Go straight or right                                330 samples
-|-----|-----|-----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 37: Go straight or left                                 180 samples
---|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 38: Keep right                                          1860 samples
-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|---------------------------------------------------------------------------------------

Processing Class 39: Keep left                                           270 samples
-----|-----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 40: Roundabout mandatory                                300 samples
-|-----|-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 41: End of no passing                                   210 samples
-|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 42: End of no passing by vehicles over 3.5 metric tons  210 samples
-|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Augment image size: 382789
In [17]:
# let's show some augmented images
sign_aug_classes, class_aug_indices, class_aug_counts = np.unique(y_train_aug, return_index = True, return_counts = True)

for c, c_index, c_count in zip(sign_aug_classes, class_aug_indices, class_aug_counts):
    print("Class %i: %-*s  %s samples" % (c, col_width, signnames[c], str(c_count)))
    fig = plt.figure(figsize = (18, 3))
    fig.subplots_adjust(left = 0, right = 1, bottom = 0, top = 1, hspace = 0.05, wspace = 0.05)
    random_indices = random.sample(range(c_index, c_index + c_count), 10)
    for i in range(10):
        axis = fig.add_subplot(1, 10, i + 1, xticks=[], yticks=[])
        axis.imshow(X_train_aug[random_indices[i]])
    plt.show()
    print("--------------------------------------------------------------------------------------\n")
    
Class 0: Speed limit (20km/h)                                1980 samples
--------------------------------------------------------------------------------------

Class 1: Speed limit (30km/h)                                21780 samples
--------------------------------------------------------------------------------------

Class 2: Speed limit (50km/h)                                22110 samples
--------------------------------------------------------------------------------------

Class 3: Speed limit (60km/h)                                13860 samples
--------------------------------------------------------------------------------------

Class 4: Speed limit (70km/h)                                19470 samples
--------------------------------------------------------------------------------------

Class 5: Speed limit (80km/h)                                18150 samples
--------------------------------------------------------------------------------------

Class 6: End of speed limit (80km/h)                         3960 samples
--------------------------------------------------------------------------------------

Class 7: Speed limit (100km/h)                               14190 samples
--------------------------------------------------------------------------------------

Class 8: Speed limit (120km/h)                               13860 samples
--------------------------------------------------------------------------------------

Class 9: No passing                                          14520 samples
--------------------------------------------------------------------------------------

Class 10: No passing for vehicles over 3.5 metric tons        19800 samples
--------------------------------------------------------------------------------------

Class 11: Right-of-way at the next intersection               12870 samples
--------------------------------------------------------------------------------------

Class 12: Priority road                                       20790 samples
--------------------------------------------------------------------------------------

Class 13: Yield                                               21120 samples
--------------------------------------------------------------------------------------

Class 14: Stop                                                7590 samples
--------------------------------------------------------------------------------------

Class 15: No vehicles                                         5940 samples
--------------------------------------------------------------------------------------

Class 16: Vehicles over 3.5 metric tons prohibited            3960 samples
--------------------------------------------------------------------------------------

Class 17: No entry                                            10890 samples
--------------------------------------------------------------------------------------

Class 18: General caution                                     11880 samples
--------------------------------------------------------------------------------------

Class 19: Dangerous curve to the left                         1980 samples
--------------------------------------------------------------------------------------

Class 20: Dangerous curve to the right                        3300 samples
--------------------------------------------------------------------------------------

Class 21: Double curve                                        2970 samples
--------------------------------------------------------------------------------------

Class 22: Bumpy road                                          3630 samples
--------------------------------------------------------------------------------------

Class 23: Slippery road                                       4950 samples
--------------------------------------------------------------------------------------

Class 24: Road narrows on the right                           2640 samples
--------------------------------------------------------------------------------------

Class 25: Road work                                           14850 samples
--------------------------------------------------------------------------------------

Class 26: Traffic signals                                     5940 samples
--------------------------------------------------------------------------------------

Class 27: Pedestrians                                         2310 samples
--------------------------------------------------------------------------------------

Class 28: Children crossing                                   5280 samples
--------------------------------------------------------------------------------------

Class 29: Bicycles crossing                                   2640 samples
--------------------------------------------------------------------------------------

Class 30: Beware of ice/snow                                  4290 samples
--------------------------------------------------------------------------------------

Class 31: Wild animals crossing                               7590 samples
--------------------------------------------------------------------------------------

Class 32: End of all speed and passing limits                 2310 samples
--------------------------------------------------------------------------------------

Class 33: Turn right ahead                                    6589 samples
--------------------------------------------------------------------------------------

Class 34: Turn left ahead                                     3960 samples
--------------------------------------------------------------------------------------

Class 35: Ahead only                                          11880 samples
--------------------------------------------------------------------------------------

Class 36: Go straight or right                                3630 samples
--------------------------------------------------------------------------------------

Class 37: Go straight or left                                 1980 samples
--------------------------------------------------------------------------------------

Class 38: Keep right                                          20460 samples
--------------------------------------------------------------------------------------

Class 39: Keep left                                           2970 samples
--------------------------------------------------------------------------------------

Class 40: Roundabout mandatory                                3300 samples
--------------------------------------------------------------------------------------

Class 41: End of no passing                                   2310 samples
--------------------------------------------------------------------------------------

Class 42: End of no passing by vehicles over 3.5 metric tons  2310 samples
--------------------------------------------------------------------------------------

In [18]:
# histogram of label frequency - after augmented
hist, bins = np.histogram(y_train_aug, bins=n_classes)
center = (bins[:-1] + bins[1:]) / 2
plt.title("Distribution of augmentation train dataset")
plt.xlabel("Class number")
plt.ylabel("No image")
plt.bar(center, hist)
plt.show()
In [19]:
sign_classes, class_indices, class_counts = np.unique(y_valid, return_index = True, return_counts = True)
X_valid_aug = []
y_valid_aug = []

n_aug = 5
for c, c_index, c_count in zip(sign_classes, class_indices, class_counts):
    print("Processing Class %i: %-*s  %s samples" % (c, col_width, signnames[c], str(c_count)))
    for i in range(c_index, c_index + c_count):
        img = X_valid[i]
        y = y_valid[i]
        X_valid_aug.append(img)
        y_valid_aug.append(y)
        for j in range(n_aug):
            X_valid_aug.append(augment_image(img))
            y_valid_aug.append(y)
        if i%10 == 0:
            print('-', end='')
        if i%50 == 0:
            print('|', end='')
    print("--------------------------------------------------------------------------------------\n")
print('Augment validation image size:', len(X_valid_aug))
Processing Class 0: Speed limit (20km/h)                                30 samples
-----------------------------------------------------------------------------------------

Processing Class 1: Speed limit (30km/h)                                240 samples
-|-----|-----|-----|-----|-----------------------------------------------------------------------------------------

Processing Class 2: Speed limit (50km/h)                                240 samples
----|-----|-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 3: Speed limit (60km/h)                                150 samples
-|-----|-----|------------------------------------------------------------------------------------------

Processing Class 4: Speed limit (70km/h)                                210 samples
---|-----|-----|-----|-----------------------------------------------------------------------------------------

Processing Class 5: Speed limit (80km/h)                                210 samples
----|-----|-----|-----|----------------------------------------------------------------------------------------

Processing Class 6: End of speed limit (80km/h)                         60 samples
-|-----|--------------------------------------------------------------------------------------

Processing Class 7: Speed limit (100km/h)                               150 samples
-|-----|-----|------------------------------------------------------------------------------------------

Processing Class 8: Speed limit (120km/h)                               150 samples
--|-----|-----|-----------------------------------------------------------------------------------------

Processing Class 9: No passing                                          150 samples
----|-----|-----|---------------------------------------------------------------------------------------

Processing Class 10: No passing for vehicles over 3.5 metric tons        210 samples
--|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 11: Right-of-way at the next intersection               150 samples
--|-----|-----|-----------------------------------------------------------------------------------------

Processing Class 12: Priority road                                       210 samples
-----|-----|-----|-----|---------------------------------------------------------------------------------------

Processing Class 13: Yield                                               240 samples
-----|-----|-----|-----|------------------------------------------------------------------------------------------

Processing Class 14: Stop                                                90 samples
----|-----|--------------------------------------------------------------------------------------

Processing Class 15: No vehicles                                         90 samples
-----|------------------------------------------------------------------------------------------

Processing Class 16: Vehicles over 3.5 metric tons prohibited            60 samples
--|------------------------------------------------------------------------------------------

Processing Class 17: No entry                                            120 samples
-|-----|-----|---------------------------------------------------------------------------------------

Processing Class 18: General caution                                     120 samples
---|-----|------------------------------------------------------------------------------------------

Processing Class 19: Dangerous curve to the left                         30 samples
-|----------------------------------------------------------------------------------------

Processing Class 20: Dangerous curve to the right                        60 samples
-|-----|--------------------------------------------------------------------------------------

Processing Class 21: Double curve                                        60 samples
--|------------------------------------------------------------------------------------------

Processing Class 22: Bumpy road                                          60 samples
-|-----|--------------------------------------------------------------------------------------

Processing Class 23: Slippery road                                       60 samples
--|------------------------------------------------------------------------------------------

Processing Class 24: Road narrows on the right                           30 samples
--|---------------------------------------------------------------------------------------

Processing Class 25: Road work                                           150 samples
-----|-----|-----|--------------------------------------------------------------------------------------

Processing Class 26: Traffic signals                                     60 samples
---|-----------------------------------------------------------------------------------------

Processing Class 27: Pedestrians                                         30 samples
---|--------------------------------------------------------------------------------------

Processing Class 28: Children crossing                                   60 samples
-|-----|--------------------------------------------------------------------------------------

Processing Class 29: Bicycles crossing                                   30 samples
-----------------------------------------------------------------------------------------

Processing Class 30: Beware of ice/snow                                  60 samples
-|-----|--------------------------------------------------------------------------------------

Processing Class 31: Wild animals crossing                               90 samples
---|-----|---------------------------------------------------------------------------------------

Processing Class 32: End of all speed and passing limits                 30 samples
-|----------------------------------------------------------------------------------------

Processing Class 33: Turn right ahead                                    90 samples
-----|------------------------------------------------------------------------------------------

Processing Class 34: Turn left ahead                                     60 samples
----|----------------------------------------------------------------------------------------

Processing Class 35: Ahead only                                          120 samples
-|-----|-----|---------------------------------------------------------------------------------------

Processing Class 36: Go straight or right                                60 samples
----|----------------------------------------------------------------------------------------

Processing Class 37: Go straight or left                                 30 samples
-----------------------------------------------------------------------------------------

Processing Class 38: Keep right                                          210 samples
---|-----|-----|-----|-----------------------------------------------------------------------------------------

Processing Class 39: Keep left                                           30 samples
-----------------------------------------------------------------------------------------

Processing Class 40: Roundabout mandatory                                60 samples
--|------------------------------------------------------------------------------------------

Processing Class 41: End of no passing                                   30 samples
-|----------------------------------------------------------------------------------------

Processing Class 42: End of no passing by vehicles over 3.5 metric tons  30 samples
--|---------------------------------------------------------------------------------------

Augment validation image size: 26460
In [20]:
# let's show some augmented validation images
sign_aug_classes, class_aug_indices, class_aug_counts = np.unique(y_valid_aug, return_index = True, return_counts = True)

for c, c_index, c_count in zip(sign_aug_classes, class_aug_indices, class_aug_counts):
    print("Class %i: %-*s  %s samples" % (c, col_width, signnames[c], str(c_count)))
    fig = plt.figure(figsize = (18, 3))
    fig.subplots_adjust(left = 0, right = 1, bottom = 0, top = 1, hspace = 0.05, wspace = 0.05)
    random_indices = random.sample(range(c_index, c_index + c_count), 10)
    for i in range(10):
        axis = fig.add_subplot(1, 10, i + 1, xticks=[], yticks=[])
        axis.imshow(X_valid_aug[random_indices[i]])
    plt.show()
    print("--------------------------------------------------------------------------------------\n")
Class 0: Speed limit (20km/h)                                180 samples
--------------------------------------------------------------------------------------

Class 1: Speed limit (30km/h)                                1440 samples
--------------------------------------------------------------------------------------

Class 2: Speed limit (50km/h)                                1440 samples
--------------------------------------------------------------------------------------

Class 3: Speed limit (60km/h)                                900 samples
--------------------------------------------------------------------------------------

Class 4: Speed limit (70km/h)                                1260 samples
--------------------------------------------------------------------------------------

Class 5: Speed limit (80km/h)                                1260 samples
--------------------------------------------------------------------------------------

Class 6: End of speed limit (80km/h)                         360 samples
--------------------------------------------------------------------------------------

Class 7: Speed limit (100km/h)                               900 samples
--------------------------------------------------------------------------------------

Class 8: Speed limit (120km/h)                               900 samples
--------------------------------------------------------------------------------------

Class 9: No passing                                          900 samples
--------------------------------------------------------------------------------------

Class 10: No passing for vehicles over 3.5 metric tons        1260 samples
--------------------------------------------------------------------------------------

Class 11: Right-of-way at the next intersection               900 samples
--------------------------------------------------------------------------------------

Class 12: Priority road                                       1260 samples
--------------------------------------------------------------------------------------

Class 13: Yield                                               1440 samples
--------------------------------------------------------------------------------------

Class 14: Stop                                                540 samples
--------------------------------------------------------------------------------------

Class 15: No vehicles                                         540 samples
--------------------------------------------------------------------------------------

Class 16: Vehicles over 3.5 metric tons prohibited            360 samples
--------------------------------------------------------------------------------------

Class 17: No entry                                            720 samples
--------------------------------------------------------------------------------------

Class 18: General caution                                     720 samples
--------------------------------------------------------------------------------------

Class 19: Dangerous curve to the left                         180 samples
--------------------------------------------------------------------------------------

Class 20: Dangerous curve to the right                        360 samples
--------------------------------------------------------------------------------------

Class 21: Double curve                                        360 samples
--------------------------------------------------------------------------------------

Class 22: Bumpy road                                          360 samples
--------------------------------------------------------------------------------------

Class 23: Slippery road                                       360 samples
--------------------------------------------------------------------------------------

Class 24: Road narrows on the right                           180 samples
--------------------------------------------------------------------------------------

Class 25: Road work                                           900 samples
--------------------------------------------------------------------------------------

Class 26: Traffic signals                                     360 samples
--------------------------------------------------------------------------------------

Class 27: Pedestrians                                         180 samples
--------------------------------------------------------------------------------------

Class 28: Children crossing                                   360 samples
--------------------------------------------------------------------------------------

Class 29: Bicycles crossing                                   180 samples
--------------------------------------------------------------------------------------

Class 30: Beware of ice/snow                                  360 samples
--------------------------------------------------------------------------------------

Class 31: Wild animals crossing                               540 samples
--------------------------------------------------------------------------------------

Class 32: End of all speed and passing limits                 180 samples
--------------------------------------------------------------------------------------

Class 33: Turn right ahead                                    540 samples
--------------------------------------------------------------------------------------

Class 34: Turn left ahead                                     360 samples
--------------------------------------------------------------------------------------

Class 35: Ahead only                                          720 samples
--------------------------------------------------------------------------------------

Class 36: Go straight or right                                360 samples
--------------------------------------------------------------------------------------

Class 37: Go straight or left                                 180 samples
--------------------------------------------------------------------------------------

Class 38: Keep right                                          1260 samples
--------------------------------------------------------------------------------------

Class 39: Keep left                                           180 samples
--------------------------------------------------------------------------------------

Class 40: Roundabout mandatory                                360 samples
--------------------------------------------------------------------------------------

Class 41: End of no passing                                   180 samples
--------------------------------------------------------------------------------------

Class 42: End of no passing by vehicles over 3.5 metric tons  180 samples
--------------------------------------------------------------------------------------

In [21]:
def grayscale(img):
    return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

def grayscale_images(images):
    return np.sum(images/3, axis=3, keepdims=True)

# Convert to grayscale images
X_train_aug_ar = np.array(X_train_aug)
X_train_gray = grayscale_images(X_train_aug_ar)

X_valid_aug_ar = np.array(X_valid_aug)
X_valid_gray = grayscale_images(X_valid_aug_ar)
In [22]:
# Normalized images
def normalized_images(images):
    return (images - 128)/128

# Normalized images
X_train_normalized = normalized_images(X_train_gray)
X_valid_normalized = normalized_images(X_valid_gray)
In [23]:
# Shuffle data
from sklearn.utils import shuffle

X_train_normalized, y_train_aug = shuffle(X_train_normalized, y_train_aug)
X_valid_normalized, y_valid_aug = shuffle(X_train_normalized, y_train_aug)
In [24]:
import tensorflow as tf

EPOCHS = 60
BATCH_SIZE = 128
In [25]:
from tensorflow.contrib.layers import flatten

keep_prob = tf.placeholder(tf.float32)

def LeNet(x):    
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1
    
    # Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
    # Need a filter height, width = 5 - strides 2 - VALID PADDING
    # VALID Padding, the output height and width are computed as:
    #out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))
    # (32-5 + 1)/1
    conv1_weights = tf.Variable(tf.truncated_normal(shape=(5,5,1,6), mean = mu, stddev = sigma))
    conv1_bias = tf.Variable(tf.zeros(6))
    conv1_strides = [1, 1, 1, 1]
    conv1_padding = 'VALID'
    conv1_layer = tf.nn.bias_add(tf.nn.conv2d(x, conv1_weights, conv1_strides, conv1_padding), conv1_bias)
    # Activation.
    # Choose relu
    conv1_layer = tf.nn.relu(conv1_layer)
    # Pooling. Input = 28x28x6. Output = 14x14x6.
    # SAME Padding
    # out_height = ceil(float(in_height) / float(strides[1]))
    conv1_pksize = [1,2,2, 1]
    conv1_pstrides = [1,2,2, 1]
    conv1_kpadding = 'SAME'
    conv1_layer = tf.nn.max_pool(conv1_layer, conv1_pksize, conv1_pstrides, conv1_kpadding)
    
    
    # Layer 2: Convolutional. Output = 10x10x16.
    # Input from layer 1: 14x14x6
    # (14-5+1)/1 - filter width - height = 5, strides 1
    conv2_weights = tf.Variable(tf.truncated_normal([5,5,6,16]))
    conv2_bias = tf.Variable(tf.zeros(16))
    conv2_strides = [1, 1, 1, 1]
    conv2_padding = 'VALID'
    conv2_layer = tf.nn.bias_add(tf.nn.conv2d(conv1_layer, conv2_weights, conv2_strides, conv2_padding), conv2_bias)
    # Activation.
    # Choose RELU
    conv2_layer = tf.nn.relu(conv2_layer)
    # Pooling. Input = 10x10x16. Output = 5x5x16.
    # SAME PADDING with strides = 2
    conv2_pksize = [1, 2, 2, 1]
    conv2_pstrides = [1, 2, 2, 1]
    conv2_ppadding = 'SAME'
    conv2_layer = tf.nn.max_pool(conv2_layer, conv2_pksize, conv2_pstrides, conv2_ppadding)

    # Flatten. Input = 5x5x16. Output = 400.
    fc = flatten(conv2_layer)
    
    # Layer 3: Fully Connected. Input = 400. Output = 120.
    fc1_weights = tf.Variable(tf.truncated_normal(shape=(400,120), mean=mu, stddev = sigma))
    fc1_bias = tf.Variable(tf.zeros(120))
    fc1_layer = tf.matmul(fc, fc1_weights) + fc1_bias
    # Activation.
    fc1_layer = tf.nn.relu(fc1_layer)
    
    # Dropout
    fc1_layer = tf.nn.dropout(fc1_layer, keep_prob)
    
    # Layer 4: Fully Connected. Input = 120. Output = 84.
    fc2_w = tf.Variable(tf.truncated_normal(shape=(120,84), mean=mu, stddev = sigma))
    fc2_b = tf.Variable(tf.zeros(84))
    fc2_layer = tf.matmul(fc1_layer, fc2_w) + fc2_b
    
    # Activation.
    fc2_layer = tf.nn.relu(fc2_layer)
    
    fc2_layer = tf.nn.dropout(fc2_layer, keep_prob)
       
    # Layer 5: Fully Connected. Input = 84. Output = 43.
    fc3_w = tf.Variable(tf.truncated_normal(shape=(84,43), mean=mu, stddev = sigma))
    fc3_b = tf.Variable(tf.zeros(43))
    logits = tf.matmul(fc2_layer, fc3_w) + fc3_b
    return logits
In [26]:
# Multi-Scale Convolutional Neural Networks - Pierre Sermanet and Yann LeCun
# http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf

def LeNet_Pierre_Yann(x, mu=0, sigma=0.1):
     # Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
    # Need a filter height, width = 5 - strides 2 - VALID PADDING
    # VALID Padding, the output height and width are computed as:
    #out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))
    # (32-5 + 1)/1
    conv1_weights = tf.Variable(tf.truncated_normal(shape=(5,5,1,6), mean = mu, stddev = sigma))
    conv1_bias = tf.Variable(tf.zeros(6))
    conv1_strides = [1, 1, 1, 1]
    conv1_padding = 'VALID'
    conv1_layer = tf.nn.bias_add(tf.nn.conv2d(x, conv1_weights, conv1_strides, conv1_padding), conv1_bias)
    
     # Activation.
    # Choose relu
    conv1_layer = tf.nn.relu(conv1_layer)
    # Pooling. Input = 28x28x6. Output = 14x14x6.
    # SAME Padding
    # out_height = ceil(float(in_height) / float(strides[1]))
    conv1_pksize = [1,2,2, 1]
    conv1_pstrides = [1,2,2, 1]
    conv1_kpadding = 'SAME'
    conv1_layer = tf.nn.max_pool(conv1_layer, conv1_pksize, conv1_pstrides, conv1_kpadding)
    
     # Layer 2: Convolutional. Output = 10x10x16.
    # Input from layer 1: 14x14x6
    # (14-5+1)/1 - filter width - height = 5, strides 1
    conv2_weights = tf.Variable(tf.truncated_normal(shape=(5,5,6,16), mean = mu, stddev = sigma))
    conv2_bias = tf.Variable(tf.zeros(16))
    conv2_strides = [1, 1, 1, 1]
    conv2_padding = 'VALID'
    conv2_layer = tf.nn.bias_add(tf.nn.conv2d(conv1_layer, conv2_weights, conv2_strides, conv2_padding), conv2_bias)
    # Activation.
    # Choose RELU
    conv2_layer = tf.nn.relu(conv2_layer)
    # Pooling. Input = 10x10x16. Output = 5x5x16.
    # SAME PADDING with strides = 2
    conv2_pksize = [1, 2, 2, 1]
    conv2_pstrides = [1, 2, 2, 1]
    conv2_ppadding = 'SAME'
    conv2_layer = tf.nn.max_pool(conv2_layer, conv2_pksize, conv2_pstrides, conv2_ppadding)
    
    
    # Layer 3: Convolutional. Input: 5x5x16
    # Filter 3,3, 50
    # Output (5 - 3 + 1)/1 = 3 => 3x3x50
    conv3_weights = tf.Variable(tf.truncated_normal(shape=(3,3,16,50), mean = mu, stddev = sigma))
    conv3_bias = tf.Variable(tf.zeros(50))
    conv3_strides = [1,1,1,1]
    conv3_padding = 'VALID'
    conv3_layer = tf.nn.bias_add(tf.nn.conv2d(conv2_layer, conv3_weights, conv3_strides, conv3_padding), conv3_bias)
    
    # RELU activation
    conv3_layer = tf.nn.relu(conv3_layer)
    
    
    # Flatten layer 2 - Input = 5x5x16. Output = 400.
    fc_layer2_flat = flatten(conv2_layer)
    print('Layer 2 flat shape:', fc_layer2_flat.shape)
    
    # Flatten layer 3 - Input = 3x3x50. Output = 450
    fc_layer3_flat = flatten(conv3_layer)
    print('Layer 3 flat shape:', fc_layer3_flat.shape)
    
    # Concat layer 2 flat and layer 3 flat. Input = 400 + 450. Output = 850
    fc = tf.concat([fc_layer2_flat, fc_layer3_flat], 1)
    print("x shape:",fc.shape)
    
     # Dropout
    fc_dropout = tf.nn.dropout(fc, keep_prob)
    
    # TODO: Layer 4: Fully Connected. Input = 850. Output = 43.
    fc1_w = tf.Variable(tf.truncated_normal(shape=(850, 43), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(43))    
    logits = tf.add(tf.matmul(fc_dropout, fc1_w), fc1_b)
    
    return logits
    
    
    
In [27]:
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, 43)
In [28]:
rate = 0.001

#logits = LeNet(x)
logits = LeNet_Pierre_Yann(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
Layer 2 flat shape: (?, 400)
Layer 3 flat shape: (?, 450)
x shape: (?, 850)
In [29]:
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0 })
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples
In [31]:
from timeit import default_timer as timer

validation_accuracies = []
start_time = timer()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train_normalized)
    
    
    print("Training numer of examples...", num_examples)
    print()
    for i in range(EPOCHS):
        start_epoch_time = timer()
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train_normalized[offset:end], y_train_aug[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 0.5  })
            if (offset % 200 == 0):
                print('-', end='' )
            if (offset % 900 == 0):
                print('|', end='' )
                
            
        
        end_epoch_time = timer()
        duration_epoch = (end_epoch_time - start_epoch_time)/60
        print()
        print("EPOCH {} ...".format(i+1))
        print("Training time: %4.2f mins"  %duration_epoch)
        validation_accuracy = evaluate(X_valid_normalized, y_valid_aug)
        validation_accuracies.append(validation_accuracy)
        end_valid_epoch_time = timer()
        duration_valid_epoch = (end_valid_epoch_time - start_epoch_time) / 60
        print("Included validation time: %4.2f mins"  %duration_valid_epoch)
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()
        
    end_time = timer()
    duration = (end_time - start_time)/60
    print("Duration time: %4.2f mins" %duration)
    #saver.save(sess, './lenet')
    saver.save(sess, './lenetyann')
    print("Model saved")
Training numer of examples... 382789

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 1 ...
Training time: %4.1f mins 1.4060929316705237
Included validation time: %4.1f mins 1.7867900638249365
Validation Accuracy = 0.966

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 2 ...
Training time: %4.1f mins 1.3949481903827061
Included validation time: %4.1f mins 1.77216908574819
Validation Accuracy = 0.979

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 3 ...
Training time: %4.1f mins 1.390923050637684
Included validation time: %4.1f mins 1.7767191019576487
Validation Accuracy = 0.983

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 4 ...
Training time: %4.1f mins 1.3983684845830784
Included validation time: %4.1f mins 1.7829484066470493
Validation Accuracy = 0.986

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 5 ...
Training time: %4.1f mins 1.3946736455978965
Included validation time: %4.1f mins 1.7749389384987126
Validation Accuracy = 0.988

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 6 ...
Training time: %4.1f mins 1.3949631453834457
Included validation time: %4.1f mins 1.7821319828319702
Validation Accuracy = 0.989

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 7 ...
Training time: %4.1f mins 1.3919692993792088
Included validation time: %4.1f mins 1.7771027482677841
Validation Accuracy = 0.990

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 8 ...
Training time: %4.1f mins 1.3884538944843579
Included validation time: %4.1f mins 1.7666376171608968
Validation Accuracy = 0.991

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 9 ...
Training time: %4.1f mins 1.389886008163512
Included validation time: %4.1f mins 1.7720109307836935
Validation Accuracy = 0.990

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 10 ...
Training time: %4.1f mins 1.390154576131738
Included validation time: %4.1f mins 1.7700823836519097
Validation Accuracy = 0.992

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 11 ...
Training time: %4.1f mins 1.3958486784081818
Included validation time: %4.1f mins 1.7726512173474285
Validation Accuracy = 0.990

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 12 ...
Training time: %4.1f mins 1.3925909453250331
Included validation time: %4.1f mins 1.773173574529244
Validation Accuracy = 0.990

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 13 ...
Training time: %4.1f mins 1.3896648037452906
Included validation time: %4.1f mins 1.7761242246855886
Validation Accuracy = 0.990

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 14 ...
Training time: %4.1f mins 1.3958068406920765
Included validation time: %4.1f mins 1.7724163383046136
Validation Accuracy = 0.992

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 15 ...
Training time: %4.1f mins 1.39583974687741
Included validation time: %4.1f mins 1.777081090731186
Validation Accuracy = 0.992

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 16 ...
Training time: %4.1f mins 1.393876655508215
Included validation time: %4.1f mins 1.777525531581595
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 17 ...
Training time: %4.1f mins 1.392193499981287
Included validation time: %4.1f mins 1.770454993845385
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 18 ...
Training time: %4.1f mins 1.392791513397348
Included validation time: %4.1f mins 1.7753688027591428
Validation Accuracy = 0.992

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 19 ...
Training time: %4.1f mins 1.387017042895089
Included validation time: %4.1f mins 1.7709022701846644
Validation Accuracy = 0.991

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 20 ...
Training time: %4.1f mins 1.3857059999255625
Included validation time: %4.1f mins 1.7692182800805691
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 21 ...
Training time: %4.1f mins 1.394605941173404
Included validation time: %4.1f mins 1.7700513487855536
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 22 ...
Training time: %4.1f mins 1.3852941024008487
Included validation time: %4.1f mins 1.7661910820920108
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 23 ...
Training time: %4.1f mins 1.3846806415316906
Included validation time: %4.1f mins 1.7607792535106455
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 24 ...
Training time: %4.1f mins 1.388575395441838
Included validation time: %4.1f mins 1.7641424128693644
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 25 ...
Training time: %4.1f mins 1.3861088466941889
Included validation time: %4.1f mins 1.764038458767171
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 26 ...
Training time: %4.1f mins 1.3850709644591386
Included validation time: %4.1f mins 1.7634760470651751
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 27 ...
Training time: %4.1f mins 1.387926042570901
Included validation time: %4.1f mins 1.7650789276730545
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 28 ...
Training time: %4.1f mins 1.3920774730206025
Included validation time: %4.1f mins 1.7797433296808929
Validation Accuracy = 0.992

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 29 ...
Training time: %4.1f mins 1.393364779786187
Included validation time: %4.1f mins 1.774225323186124
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 30 ...
Training time: %4.1f mins 1.3949996335117627
Included validation time: %4.1f mins 1.7739928234657782
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 31 ...
Training time: %4.1f mins 1.3923040477614526
Included validation time: %4.1f mins 1.7693649686805506
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 32 ...
Training time: %4.1f mins 1.3901917899793261
Included validation time: %4.1f mins 1.7797155138978875
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 33 ...
Training time: %4.1f mins 1.3921821683932043
Included validation time: %4.1f mins 1.7718978740883282
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 34 ...
Training time: %4.1f mins 1.3938341283587912
Included validation time: %4.1f mins 1.7731655916172333
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 35 ...
Training time: %4.1f mins 1.391983181352172
Included validation time: %4.1f mins 1.7756080931384
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 36 ...
Training time: %4.1f mins 1.3935517147035776
Included validation time: %4.1f mins 1.7758920670900504
Validation Accuracy = 0.995

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 37 ...
Training time: %4.1f mins 1.3913519662793532
Included validation time: %4.1f mins 1.7707927332277753
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 38 ...
Training time: %4.1f mins 1.390029685028503
Included validation time: %4.1f mins 1.7742496607003204
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 39 ...
Training time: %4.1f mins 1.3902933803101785
Included validation time: %4.1f mins 1.7688426944380733
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 40 ...
Training time: %4.1f mins 1.396796250063365
Included validation time: %4.1f mins 1.773818723412114
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 41 ...
Training time: %4.1f mins 1.3928903926483447
Included validation time: %4.1f mins 1.772282292771115
Validation Accuracy = 0.992

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 42 ...
Training time: %4.1f mins 1.3887599614041695
Included validation time: %4.1f mins 1.768273310647343
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 43 ...
Training time: %4.1f mins 1.3949258071268409
Included validation time: %4.1f mins 1.7761430830192846
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 44 ...
Training time: %4.1f mins 1.3908382503405998
Included validation time: %4.1f mins 1.7770750361589611
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 45 ...
Training time: %4.1f mins 1.3950425960927533
Included validation time: %4.1f mins 1.7762835511683381
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 46 ...
Training time: %4.1f mins 1.3967821970280057
Included validation time: %4.1f mins 1.7831505609343368
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 47 ...
Training time: %4.1f mins 1.3938979087155077
Included validation time: %4.1f mins 1.7745537785455325
Validation Accuracy = 0.987

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 48 ...
Training time: %4.1f mins 1.3888716703351747
Included validation time: %4.1f mins 1.7681656087234843
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 49 ...
Training time: %4.1f mins 1.3911133808845382
Included validation time: %4.1f mins 1.7759209455334257
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 50 ...
Training time: %4.1f mins 1.3908915181352617
Included validation time: %4.1f mins 1.7710934972131933
Validation Accuracy = 0.995

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 51 ...
Training time: %4.1f mins 1.3950098868883591
Included validation time: %4.1f mins 1.782246641293447
Validation Accuracy = 0.995

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 52 ...
Training time: %4.1f mins 1.3936061643839064
Included validation time: %4.1f mins 1.7723901605736805
Validation Accuracy = 0.995

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 53 ...
Training time: %4.1f mins 1.3891905824861472
Included validation time: %4.1f mins 1.7710344547665955
Validation Accuracy = 0.991

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 54 ...
Training time: %4.1f mins 1.3889056650994158
Included validation time: %4.1f mins 1.7671995364105137
Validation Accuracy = 0.995

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 55 ...
Training time: %4.1f mins 1.3891463084267495
Included validation time: %4.1f mins 1.76998949158492
Validation Accuracy = 0.995

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 56 ...
Training time: %4.1f mins 1.3920161601094303
Included validation time: %4.1f mins 1.772381975497016
Validation Accuracy = 0.991

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 57 ...
Training time: %4.1f mins 1.389389408832191
Included validation time: %4.1f mins 1.7686805791198368
Validation Accuracy = 0.993

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 58 ...
Training time: %4.1f mins 1.3925214266023582
Included validation time: %4.1f mins 1.7686184471826134
Validation Accuracy = 0.992

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 59 ...
Training time: %4.1f mins 1.3922872577276848
Included validation time: %4.1f mins 1.7712484538291695
Validation Accuracy = 0.994

-|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|--
EPOCH 60 ...
Training time: %4.1f mins 1.3870153892918855
Included validation time: %4.1f mins 1.7634401861656444
Validation Accuracy = 0.995

Duration time: %4.1f 106.38214023011315
Model saved
In [32]:
print('Duration time %4.1f mins' %duration)
Duration time 106.4 mins
In [33]:
X_test_gray = grayscale_images(X_test)
X_test_normalized = normalized_images(X_test_gray)
In [34]:
# Evaluate the test dataset

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver2 = tf.train.import_meta_graph('./lenetyann.meta')
    saver2.restore(sess, "./lenetyann")
    test_accuracy = evaluate(X_test_normalized, y_test)
    print("Test Set Accuracy = {:.3f}".format(test_accuracy))
INFO:tensorflow:Restoring parameters from ./lenetyann
Test Set Accuracy = 0.951

Model Architecture

In [ ]:
### Define your architecture here.
### Feel free to use as many code cells as needed.

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [ ]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [ ]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.

Predict the Sign Type for Each Image

In [ ]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.

Analyze Performance

In [ ]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [ ]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.


Step 4 (Optional): Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [ ]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(15,15))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")